<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Login extends Controller_Base_Frontend {
	
	public function action_index() {
		$this->view->body->content = Login::view(isset($_GET["redirect"]) ? $_GET["redirect"] : '');
		$this->response->body($this->view);
	}

	public function action_login() {
		try {
			if (Model_User::login($_POST['email'], $_POST['password'])) {
				if (isset($_POST["redirect"]) && !empty($_POST["redirect"])) {
					$redirect = $_POST["redirect"];
				} else {
					if (Model_User::logged_in('admin')) {
						$redirect = "adm";
					} else {
						$redirect = "/";
					}
				}
				Request::current()->redirect($redirect);
			} else {
				$errors = array("login" => __("Invalid login"));
				$this->response->body(Json_View::factory(array("content" => $errors)));
			}
		} catch (Exception $e) {
			$errors = array("_external" => array("Login" => $e->getMessage()));
			$this->response->body(Json_View::factory(array("content" => $errors)));
		}
	}

	public function action_logout() {
		Model_User::logout();
		Request::current()->redirect('/');
	}

} // End Login